﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace MessageLibrary
{
    /// <summary>
    /// Composer pro skladani a rozkladani message.
    /// </summary>
    public class MessageComposer
    {
        /// <summary>
        /// Serializuje zpravu do binarni podoby.
        /// </summary>
        /// <param name="msgType"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static byte[] Serialize(int msgType, Messages.Message msg)
        {
            MemoryStream stream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(stream, msgType);
            formatter.Serialize(stream, msg);

            return stream.ToArray();
        }

        public static void Deserialize(byte[] buffer, out int msgType, out Messages.Message msg)
        {
            MemoryStream stream = new MemoryStream(buffer);
            BinaryFormatter formatter = new BinaryFormatter();
            msgType = (int)formatter.Deserialize(stream);
            msg = (Messages.Message)formatter.Deserialize(stream);
        }
    }
}
